﻿using System;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Windows.Forms;
using System.Diagnostics;

namespace fm2
{
	public class ProgressBarEx : ProgressBar
	{
		private int counter = 0;
		public int Counter {
			get {
				return counter;
			}
			set {
				counter = value;
				Text = counter > 0 ? counter.ToString() : "";
			}
		}
		private LinearGradientBrush brushNormal;
		private LinearGradientBrush brushWarning;

		public ProgressBarEx()
		{
			this.SetStyle(ControlStyles.UserPaint, true);
			Rectangle rect = new Rectangle(0, 0, 1, this.Height - 4);
			brushNormal = new LinearGradientBrush(rect, Color.FromArgb(0, 255, 0), Color.FromArgb(0, 150, 0), LinearGradientMode.Vertical);
			brushWarning = new LinearGradientBrush(rect, Color.FromArgb(255, 0, 0), Color.FromArgb(150, 0, 0), LinearGradientMode.Vertical);
		}
		protected override void OnPaintBackground(PaintEventArgs pevent)
		{
			// None... Helps control the flicker.
		}
		protected override void OnPaint(PaintEventArgs e)
		{
			const int inset = 2; // A single inset value to control teh sizing of the inner rect.
			using (Image offscreenImage = new Bitmap(this.Width, this.Height))
			{
				using (Graphics offscreen = Graphics.FromImage(offscreenImage))
				{
					Rectangle rect = new Rectangle(0, 0, this.Width, this.Height);
					if (ProgressBarRenderer.IsSupported) {
						ProgressBarRenderer.DrawHorizontalBar(offscreen, rect);
					}
					rect.Inflate(new Size(-inset, -inset)); // Deflate inner rect.
					rect.Width = (int)(rect.Width * ((double)this.Value / this.Maximum));
					if (rect.Width > 0) {
						LinearGradientBrush brush = Counter > 0 ? brushWarning : brushNormal;
						offscreen.FillRectangle(brush, inset, inset, rect.Width, rect.Height);
					}
					e.Graphics.DrawImage(offscreenImage, 0, 0);
					if (Text.Length > 0) {
						SizeF sf = e.Graphics.MeasureString(Text, SystemFonts.DefaultFont);
						e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
						e.Graphics.DrawString(Text, SystemFonts.DefaultFont, Brushes.Black,
											  Width/2 - (sf.Width/2) + 2, Height/2 - (sf.Height/2));
					}
				}
			}
		}
	}
}
